package com.wt.struggle.goodbye.user.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.view.View
import com.tencent.connect.UserInfo
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import com.wt.struggle.goodbye.App
import com.wt.struggle.goodbye.MainActivity
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ProActivity
import com.wt.struggle.goodbye.base.Send
import com.wt.struggle.goodbye.base.Share
import com.wt.struggle.goodbye.db.DbUtil
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import com.wt.struggle.goodbye.wxapi.WXEntryActivity
import com.wt.struggle.goodbye.wxutil.WXPay
import com.xin.lv.yang.utils.net.Time
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.login_layout.*
import org.json.JSONObject
import com.wt.struggle.goodbye.wxutil.Contact
import org.json.JSONException

/**
 * 登录
 */
class LoginActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {
            1234 -> {
                val num = arg1
                if (num > 0) {
                    btGetYan.text = ("${num}S")
                } else {
                    btGetYan.isClickable = true
                    btGetYan.text = "重新获取"
                }
            }

            Send.SEND_YAN_CODE -> {

                if (netInfo.code == Config.SUCCESS) {
                    showToastShort("发送成功，请注意查收!!")
                }
            }

            Send.LOGIN -> {

                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {

                    showToastShort("登录成功")

                    val jsonObject = JSONObject(netInfo.dataResult)
                    val token = jsonObject.optString("token")
                    val uid = jsonObject.optInt("uid")

                    Share.saveToken(this@LoginActivity, token)
                    Share.saveUid(this@LoginActivity, uid)

                    send!!.loginActivity(token, Share.getUmToken(this@LoginActivity), handler)

                    val userInfo = ProUserInfo()

                    val account = etEditText.text.toString()
                    userInfo.account = account
                    userInfo.pwd = etEditTextPwd.text.toString()

                    Share.saveAccount(this, account)

                    dbUtil!!.addAccount(userInfo)

                } else {
                    showToastShort(netInfo.dataResult!!)
                }
            }

            Send.LOGIN_ACTIVITY -> {

                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult
                    if (result != null && result != "") {

                        val json = JSONObject(result)
                        val uuid = json.optString("uuid")
                        Share.saveUuid(this, uuid)

                        val userId = json.optInt("id")
                        Share.saveUid(this@LoginActivity, userId)

                        if (joupCode == 2) {
                            startActivity(Intent(this@LoginActivity, MainActivity::class.java))

                        }

                        finish()

                    }
                }
            }

            Send.GET_USER_INFO -> {

                if (netInfo.code == Config.SUCCESS) {

                    val jsonObject = JSONObject(netInfo.dataResult)
                    val userId = jsonObject.optInt("id")
                    Share.saveUid(this@LoginActivity, userId)

                    finish()
                }
            }

            Send.THREE_LOGIN -> {

                if (netInfo.code == Config.SUCCESS) {

                    showToastShort("三方登录成功")

                    if (netInfo.dataResult != null) {

                        val jsonObject = JSONObject(netInfo.dataResult)
                        val token = jsonObject.optString("token")
                        val uid = jsonObject.optInt("uid")

                        Share.saveToken(this@LoginActivity, token)
                        Share.saveUid(this@LoginActivity, uid)

                        startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                    }

                    finish()

                }
            }

        }

    }

    var wxPay: WXPay? = null

    var joupCode = 1

    /**
     * 1 为验证码登录  2 为账号密码登录
     */
    var loginCode = 2
    var dbUtil: DbUtil? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login_layout)
        dbUtil = DbUtil(this)
        joupCode = intent.getIntExtra("code", 1)

        wxPay = WXPay(this)

        initClick()

    }

    private fun initClick() {
        imageBack.setOnClickListener {
            finish()
        }

        imageWeiChat.setOnClickListener {
            weiChatLogin()

        }

        imageQQ.setOnClickListener {
            qqLogin()

        }

        btGetYan.setOnClickListener {

            getYan()

        }

        cbAccountPwd.setOnCheckedChangeListener { compoundButton, b ->
            if (b) {
                /// 账号密码登录
                etEditTextPwd.visibility = View.VISIBLE
                pwdView.visibility = View.VISIBLE
                yanLinear.visibility = View.GONE
                loginCode = 2

            } else {
                // 手机验证码登录
                etEditTextPwd.visibility = View.GONE
                pwdView.visibility = View.GONE
                yanLinear.visibility = View.VISIBLE
                loginCode = 1
            }
        }



        tvRegister.setOnClickListener {

            startActivity(Intent(this, RegisterActivity::class.java))

            finish()

        }

        tvForget.setOnClickListener {
            startActivity(Intent(this, ForgetActivity::class.java))
        }

        btLogin.setOnClickListener {
            val code = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)
            if (code == PackageManager.PERMISSION_GRANTED) {
                if (loginCode == 1) {
                    login()
                } else if (loginCode == 2) {
                    loginByPwd()
                }

            } else {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), 888)
            }

        }
    }


    var SCOPE = "all"
    var mTencent: Tencent? = null

    private fun qqLogin() {
        if (checkApkExist(this, "com.tencent.mobileqq")) {

            mTencent = Tencent.createInstance(Contact.QQ_APP_ID, this.applicationContext)
            if (mTencent != null && !mTencent!!.isSessionValid) {
                showLoadDialog()
                mTencent!!.login(this, SCOPE, MyQQListener())

            } else {
                showToastShort("调用qq登录失败")
            }

        } else {
            showToastShort("请安装QQ")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Tencent.onActivityResultData(requestCode, resultCode, data, MyQQListener())

    }


    var openId: String = ""

    private inner class MyQQListener : IUiListener {

        override fun onComplete(o: Any) {
            val string = o.toString()

            log("qq登陆--------$string")

            try {
                val json = JSONObject(string)
                openId = json.optString("openid")
                val accessToken = json.optString("access_token")
                val expires = json.optString("expires_in")
                mTencent!!.openId = openId
                mTencent!!.setAccessToken(accessToken, expires)

                getUserInfo()

            } catch (e: JSONException) {
                e.printStackTrace()
            }

        }

        override fun onError(uiError: UiError) {
            removeLoadDialog()
            showToastShort("qq登录失败")

        }

        override fun onCancel() {
            showToastShort("已取消qq登录")
            removeLoadDialog()

        }
    }


    /**
     * 获取qq用户信息
     */
    fun getUserInfo() {
        val qqToken = mTencent!!.qqToken
        val info = UserInfo(applicationContext, qqToken)
        info.getUserInfo(object : IUiListener {
            override fun onComplete(o: Any) {

                log("result-----" + o.toString())

                val jsonObject = JSONObject(o.toString())

                val userInfo = ProUserInfo()
                userInfo.openid = openId
                userInfo.unionid = openId
                userInfo.nickName = jsonObject.optString("nickname")
                userInfo.gender = jsonObject.optString("gender")
                userInfo.avatarurl = jsonObject.optString("figureurl_2")
                send!!.qqLogin(userInfo, handler!!)

            }

            override fun onError(uiError: UiError) {

            }

            override fun onCancel() {

            }
        })
    }

    /**
     * 微信登录
     */
    private fun weiChatLogin() {

        Share.saveIsLoginOrShare(this, 2)

        WXEntryActivity.setOnBackText { code, userInfo ->
            when (code) {
                0 -> {
                    removeLoadDialog()
                    weiXinLogin(userInfo!!)
                }
            }

        }

        wxPay!!.weixinLogin()
    }


    private fun weiXinLogin(userInfo: ProUserInfo?) {
        send!!.weiXinLogin(userInfo, handler!!)


    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 888) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (loginCode == 1) {
                    login()
                } else if (loginCode == 2) {
                    loginByPwd()
                }

            } else {
                showToastShort("请检查获取手机状态权限")
            }
        }
    }


    /**
     * 账号密码登录
     */
    fun loginByPwd() {
        val phone = etEditText.text.toString()
        val pwd = etEditTextPwd.text.toString()
        when {
            phone == "" -> showToastShort("请输入电话号码")
            pwd == "" -> showToastShort("请输入密码")
            else -> {
                send!!.loginByPwd(phone, pwd, getImei(this), handler!!)
                showLoadDialog("登录中")
            }
        }
    }


    /**
     * 验证码登录
     */
    fun login() {
        val phone = etEditText.text.toString()
        val yanCode = etLoginYan.text.toString()
        when {
            phone == "" -> showToastShort("请输入电话号码")
            yanCode == "" -> showToastShort("请输入验证码")
            else -> {
                send!!.loginBuyYanCode(phone, yanCode, handler!!)
                showLoadDialog("登录中")
            }
        }
    }


    private fun getYan() {
        val phone = etEditText.text.toString()
        if (phone != "") {
            Time(60, 1234, handler).start()
            btGetYan.isClickable = false

            send!!.sendYan(phone, 2, handler!!)

        } else {
            showToastShort("请输入电话号码")
        }

    }
}